package com.dy.security.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: ding-yu
 * @Date: 2022/5/24 13:54
 * @Desctiption: (描述) 过滤器，过滤登录时的请求
 */
@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {

    private static final String LOGIN_RUL="/login";
    private static final String KAPTCHA="kaptcha";
    private static final String CODE="code";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断请求为登录的时候查看验证码是否正确
        if (LOGIN_RUL.equals(request.getRequestURI()) && HttpMethod.POST.name().equals(request.getMethod())) {
            if (this.verificationCode(request)) {
                log.info("验证通过");
                filterChain.doFilter(request,response);
            }else{
                log.info("验证失败");
                response.getWriter().write("erro");
            }
        }else{
            //不是登录请求就放行过去
            log.info("不是登录请求");
            filterChain.doFilter(request,response);
        }
    }


    /**
     * 校验验证码是否合法
     * @param request request
     * @return Boolean
     */
    private Boolean verificationCode(HttpServletRequest request){
        //获取session中的验证码
        String sessionCode = (String)request.getSession().getAttribute(KAPTCHA);
        //获取前端传入的session
        String code = request.getParameter(CODE);
        //比较两个code是否相同
        if (StringUtils.isEmpty(code)) {
            //验证码不存在清空session
            request.removeAttribute(KAPTCHA);
            return false;
        }
        if (!sessionCode.equals(code)) {
            return false;
        }
        return true;
    }
}
